package gclib;

import java.util.List;
import java.util.Map;
import gclib.inventory.Armor;
import gclib.inventory.Item;
import java.util.HashMap;
import org.junit.After;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;

/**
 *
 * @author Jason
 */
public class Loader {
    private static Logger logger = LoggerFactory.getLogger(Loader.class);
    private static EntityManagerFactory EMF;
    private EntityManager em;
    private static Map<String, Object> testProperties = new HashMap<String, Object>();

    @BeforeClass
    public static void setUpClass() throws Exception {
        logger.error("starting up test case class");
        testProperties.put("hibernate.show_sql", "true");
        testProperties.put("hibernate.format_sql", "true");
//        testProperties.put("hibernate.connection.shutdown", "true");
        EMF = Persistence.createEntityManagerFactory("GCB_PU", testProperties);
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        if(EMF!=null && EMF.isOpen())
            EMF.close();
        EMF = null;
    }

    @Before
    public void setUp() {
        assertNotNull("EntityManagerFactory is null", EMF);
        em = EMF.createEntityManager();
    }

    @After
    public void tearDown() {
        if(em!=null && em.isOpen())
            em.close();
        em = null;
    }

    @Test
    public void testLoadAnItemRecord() {
        EntityTransaction entityTx = em.getTransaction();
        entityTx.begin();
        Item item = new Item();
        item.setName("Bull Test");
        item.setDescription("Simple Description");
        item.setWeight(5.5);

        Armor armor = new Armor();
        armor.setArmorType(Armor.TYPE.PLATE);
        armor.setName("Defender's Shell");
        armor.setDescription("Rather thin.");
        armor.setWeight(23.5);
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<Item> cq = em.getCriteriaBuilder().createQuery(Item.class);
        cq.from(Item.class);
        List<Item> items = em.createQuery(cq).getResultList();
        logger.debug("There are {} records", items.size());
        em.persist(item);
        em.persist(armor);
        em.flush();
        System.out.println(item);
        System.out.println(armor);
        assertNotNull("Item should be populated by IDENTITY attribute from persistent storage.", item.getItemId());
//        em.remove(item);
//        em.flush();
        entityTx.commit();
//        entityTx.rollback();
    }
}
